home *** CD-ROM | disk | FTP | other *** search
/ The Atari Compendium / The Atari Compendium (Toad Computers) (1994).iso / files / prgtools / langs / dl_exsrc.zoo / strirpl.c < prev    next >
Encoding:
C/C++ Source or Header  |  1994-07-02  |  1.1 KB  |  46 lines

  1. #include <string.h>
  2. #include <stdlib.h>
  3. #include <ctype.h>
  4. #include "extras.h"
  5.  
  6. int strirpl(string, ptrn, rpl, n)
  7.   char *string, *ptrn, *rpl;
  8.   int n;
  9. {
  10.   register char *s, *t = string;
  11.   char *u;
  12.   register int count = 0;
  13.   register char ptrn_1;
  14.   int ptrn_len = strlen(ptrn), rpl_len = strlen(rpl);
  15.   int store_len;
  16.  
  17.   if (!string || *string == '\0' || !ptrn || *ptrn == '\0' || n == 0)
  18.     return 0;
  19.  
  20.   /* At worst, the string's size could increase by a factor of
  21.      rpl_len/ptrn_len */
  22.   if (rpl_len > ptrn_len)
  23.     store_len = (strlen(string)/ptrn_len + 1) * rpl_len + 1;
  24.   else
  25.     store_len = strlen(string) + 1;
  26.  
  27.   s = u = (char *)malloc((size_t)store_len);
  28.   ptrn_1 = *ptrn;
  29.   for (;;) {
  30.     if (*t == '\0') {
  31.       *s = '\0';
  32.       break;
  33.     } else if (toupper(*t) == toupper(ptrn_1) &&
  34.            strnicmp(t, ptrn, ptrn_len) == 0 &&
  35.            (n < 0 || count < n)) {
  36.       strcpy(s, rpl);
  37.       s += rpl_len;
  38.       t += ptrn_len;
  39.       count++;
  40.     } else *s++ = *t++;
  41.   }
  42.   strcpy(string, u);
  43.   free(u);
  44.   return count;
  45. }
  46.